package com.liandu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liandu.common.Common;
import com.liandu.common.Constants;
import com.liandu.common.PageInfo;
import com.liandu.common.parent.ParentService;
import com.liandu.common.utils.DateUtil;
import com.liandu.common.utils.EntityUtil;
import com.liandu.common.utils.FastJsonUtil;
import com.liandu.entity.*;
import com.liandu.service.LdService;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class LdServiceImpl extends ParentService implements LdService {


    @Override
    public List<Market> getAllMarKet() {
        return marketDao.findAll();
    }

    @Override
    public PageInfo getAllWeight(WeighInfo weighInfo, String start, String end, String busiName) {
        //追溯码
        String traceCode = weighInfo.getTraceCode();
        Date startDate = DateUtil.parseDate(start, Constants.YYYY_MM_DD_HH_MM_SS);
        Date endDate = DateUtil.parseDate(end, Constants.YYYY_MM_DD_HH_MM_SS);
        Pageable pageable = EntityUtil.getPageable(weighInfo, Sort.by(Sort.Order.desc("insertDateTime")));
        Page<WeighInfo> page = weighInfoDao.findAllWeightInfo(traceCode,startDate,endDate,busiName,pageable);
        List<WeighInfo> list = page.getContent();
        if (list.isEmpty()) {
            return PageInfo.of(page);
        }
        Set<String> ids = list.stream().map(WeighInfo::getUploadDevice).collect(Collectors.toSet());
        //ecrId->entity
        Map<String,EcrInfo> ecrInfoMap = ecrInfoDao.findAllById(ids).stream().collect(Collectors.toMap(EcrInfo::getEcrID, Function.identity()));
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        EcrInfo ecrInfo;
        for (WeighInfo info : list) {
            ecrInfo = ecrInfoMap.get(info.getUploadDevice());
//            ecrInfo.setCalInfoList(null);
//            ecrInfo.setWeighInfoList(null);
            jsonObject = FastJsonUtil.parseJSONObject(info);
            jsonObject.put("ecrInfo",ecrInfo);
            jsonArray.add(jsonObject);
        }
        return PageInfo.of(page,jsonArray);
    }

    @Override
    public JSONArray getAllEcrInfo() {
        JSONArray jsonArray = new JSONArray();
        List<EcrInfo> ecrInfoList = ecrInfoDao.findAll();
        ecrInfoList.sort(Comparator.comparingInt(x -> Integer.parseInt(x.getBusiNo())));
        if (ecrInfoList.isEmpty()) {
            return jsonArray;
        }
        Set<String> ids = ecrInfoList.stream().map(EcrInfo::getEcrID).collect(Collectors.toSet());
        //ecrId->重量分组
        Map<String,List<WeighInfo>> weighMap = weighInfoDao.findAllByUploadDeviceIn(ids)
                .stream().collect(Collectors.groupingBy(WeighInfo::getUploadDevice));
        //标定信息
        Map<String,List<CalInfo>> claMap = calInfoDao.findAllByEcrIDIn(ids).stream().collect(Collectors.groupingBy(CalInfo::getEcrID));
        JSONObject jsonObject;
        List<CalInfo> calInfoList;
        for (EcrInfo ecrInfo : ecrInfoList) {
            jsonObject = FastJsonUtil.parseJSONObject(ecrInfo);
            calInfoList = claMap.get(ecrInfo.getEcrID());
            if (calInfoList == null || calInfoList.isEmpty()){
                jsonObject.put("flashTime",0);
            } else {
                calInfoList.sort((x,y)-> (int) (y.getInsertDateTime().getTime()-x.getInsertDateTime().getTime()));
                //1000*60*30 30分钟的毫秒数
                long time = (1000 * 60 * 30 - (System.currentTimeMillis()-calInfoList.get(0).getInsertDateTime().getTime()))/1000;
                time = Math.max(time, 0);
                jsonObject.put("flashTime",time);
            }
            jsonObject.put("tradesNum",weighMap.get(ecrInfo.getEcrID()) == null ? 0 : weighMap.get(ecrInfo.getEcrID()).size());
            jsonObject.put("totalPrice",weighMap.get(ecrInfo.getEcrID()) == null ? 0 : weighMap.get(ecrInfo.getEcrID()).stream().mapToInt(WeighInfo::getPrice).sum());
            //todo what is pos?
            jsonObject.put("posTrades",0);
            jsonObject.put("posPrice",0);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    @Override
    public List<BusiInfo> getAllBusiInfo() {
        return busiInfoDao.findAll();
    }

    @Override
    public PageInfo getAllCalInfo(CalInfo calInfo, String start, String end, String busiName) {
        Date startDate = DateUtil.parseDate(start, Constants.YYYY_MM_DD_HH_MM_SS);
        Date endDate = DateUtil.parseDate(end, Constants.YYYY_MM_DD_HH_MM_SS);
        Pageable pageable = EntityUtil.getPageable(calInfo,Sort.by(Sort.Order.desc("calDateTime")));
        Page<CalInfo> page = calInfoDao.findAllCalInfo(startDate,endDate,busiName,pageable);
        List<CalInfo> calInfoList = page.getContent();
        if (calInfoList.isEmpty()) {
            return PageInfo.of(page);
        }
        JSONArray jsonArray = new JSONArray();
        Map<String,EcrInfo> ecrInfoMap = ecrInfoDao.findAllById(calInfoList.stream().map(CalInfo::getEcrID).collect(Collectors.toSet()))
                .stream().collect(Collectors.toMap(EcrInfo::getEcrID, Function.identity()));
        JSONObject jsonObject;
        for (CalInfo info : calInfoList) {
            jsonObject = FastJsonUtil.parseJSONObject(info);
            jsonObject.put("ecrInfo",ecrInfoMap.get(info.getEcrID()));
            jsonArray.add(jsonObject);
        }
        return PageInfo.of(page,jsonArray);
    }
}
